# -*- coding: utf-8 -*-
import json
import copy
from django.forms import Media
from django.utils.html import format_html
from django.utils.encoding import force_text
from django.forms.utils import flatatt
from wagtail.wagtailadmin.rich_text import DbWhitelister, expand_db_html
from wagtail.wagtailadmin.edit_handlers import RichTextFieldPanel

from wagtail.utils.widgets import WidgetWithScript


class QuillRichTextArea(WidgetWithScript):
    @staticmethod
    def get_id_for_js(identify):
        return "{}_js".format(identify)

    def __init__(self, attrs=None):
        # Use slightly better defaults than HTML's 20x2 box
        default_attrs = {'style': 'height: 375px;'}
        if attrs:
            default_attrs.update(attrs)
        super(QuillRichTextArea, self).__init__(default_attrs)

    def render_html(self, name, value, attrs=None):
        if value is None:
            value = ''
        c_attrs = copy.deepcopy(attrs)
        c_attrs['id'] = self.get_id_for_js(c_attrs['id'])
        final_attrs = self.build_attrs(c_attrs)
        final_attrs_html = self.build_attrs(attrs, name=name)
        return format_html('''
            <div {}></div>
            <textarea style="display:none;" {}>{}</textarea>
        ''',
                           flatatt(final_attrs),
                           flatatt(final_attrs_html),
                           force_text(value))

    def get_panel(self):
        return RichTextFieldPanel

    def render(self, name, value, attrs=None):
        if value is None:
            translated_value = None
        else:
            translated_value = expand_db_html(value, for_editor=True)
        return super(QuillRichTextArea, self).render(name, translated_value, attrs)

    def value_from_datadict(self, data, files, name):
        original_value = super(QuillRichTextArea, self).value_from_datadict(data, files, name)
        if original_value is None:
            return None
        return DbWhitelister.clean(original_value)

    def render_js_init(self, id_, name, value):
        toolbarOptions = '''[
            ['bold', 'italic', 'underline', 'strike'],
            ['code-block'],

            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'indent': '-1'}, {'indent': '+1'}],

            [{'header': [1, 2, 3, 4, 5, 6, false]}],

            [{'color': []}, {'background': []}],
            [{'font': []}],
            [{'align': []}],
            ['clean']
        ]'''
        hljs_configure = '''
            {
                languages: ['javascript', 'ruby', 'python'],
                useBR: false
            }
        '''
        return """
            hljs.configure({hljs_configure});

            var quill = new Quill({0}, {{
            modules: {{
                syntax: true,
                toolbar: {toolbar}
              }},
              theme: 'snow'
            }});
            quill.root.innerHTML = unescape(`{content}`)
            quill.on('editor-change', function() {{
                $("{e_html}").val(escape(quill.root.innerHTML))
            }});
        """.format(
            json.dumps("#" + self.get_id_for_js(id_)),
            hljs_configure=hljs_configure,
            toolbar=toolbarOptions,
            content=force_text(value),
            e_html="#" + str(id_)
        )

    @property
    def media(self):
        return Media(
            css={'all': (
                'https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.0/quill.snow.min.css',
                'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/monokai-sublime.min.css'
            )},
            js=[
                'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js',
                'https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.0/quill.min.js',

            ])
